package com.git.xiaoyou11.client;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.data.redis.connection.SortParameters.Order;
import org.springframework.data.redis.connection.SortParameters.Range;
import org.springframework.data.redis.core.BulkMapper;
import org.springframework.data.redis.core.query.SortQuery;
import org.springframework.data.redis.core.query.SortQueryBuilder;
import org.springframework.data.redis.hash.HashMapper;
import org.springframework.stereotype.Service;

import com.git.xiaoyou11.domain.New;
import com.git.xiaoyou11.service.BaseClientRedisRepository;
import com.git.xiaoyou11.service.BaseClientRedisRepositoryDao;
import com.git.xiaoyou11.support.KeyGenUtils;

@Service
public class NewRedisClient extends BaseClientRedisRepository<New> implements
		BaseClientRedisRepositoryDao<New> {

	@Override
	public List<New> findEntityListByRange(Range range) {
		String nid = New.class.getSimpleName()+":*->"; 
		final String title = "title";
		final String content = "content";
		final String date = "date";
		final String externalLink = "externalLink";
		final String externalLoginName = "externalLoginName";
		final String externalLoginPwd = "externalLoginPwd";
		SortQuery<String> query = SortQueryBuilder.
				sort(KeyGenUtils.timeline(New.class.getSimpleName())).
				by(nid+content).
				alphabetical(true).
				order(Order.DESC).
				get(nid+title).
				get(nid+content).
				get(nid+date).
				get(nid+externalLink).
				get(nid+externalLoginName).
				get(nid+externalLoginPwd).
				limit(range).build();
		final HashMapper<New, String, String> postMapper  = this.getPostMapper();
		BulkMapper<New, String> bm = new BulkMapper<New, String>() {

			@Override
			public New mapBulk(List<String> bulk) {
				Map<String,String> map = new LinkedHashMap<String,String>();
				Iterator<String> it = bulk.iterator();
				
				String title = it.next();
				String content = it.next();
				String date = it.next();
				String externalLink = it.next();
				String externalLoginName = it.next();
				String externalLoginPwd = it.next();
				
				map.put("title", title);
				map.put("content", content);
				map.put("date", date);
				map.put("externalLink", externalLink);
				map.put("externalLoginName", externalLoginName);
				map.put("externalLoginPwd", externalLoginPwd);
				return postMapper.fromHash(map);
			}
		};
		return this.getTemplate().sort(query, bm);
	}

}
